<template>
    <div v-if="loading === false && item.content" style="width: 100%;padding: 4px 16px;">
        <div v-if="item.type < 2" style="width: 100%;height: 26px;display: flex;align-items: center;gap: 8px;">
            <img v-if="item.type === 0" style="width: 24px;height: 24px;" src="../assets/icon_ruru_head.png" alt="">
            <img v-if="item.type === 1" style="width: 24px;height: 24px;" src="../assets/icon_user_head.png" alt="">
            <span style="font-size: 15px;font-weight: bold;">{{ item.username }}</span>
        </div>
        <div v-if="item.type < 2"
            style="width: 100%;word-break: break-all;white-space: wrap;margin-top: 3px;font-size: 14px;padding-left: 32px;color: dimgray;user-select: text;white-space: pre-wrap;">
            <!-- {{props.item.content.replace(/(?<=\S) {1,2}(?=\S)/g, m => m.length === 2 ? ' ' : '')}} -->
            <!-- <v-md-editor :preview-only="true" v-model="props.item.content" ></v-md-editor> -->
            <!-- <v-md-preview :source="props.item.content" /> -->
            <div v-if="renderedMarkdown.think"
                style="width: 100%;font-size: 12px;color: gray;border-left: 2px solid lightgray;padding: 4px 0;padding-left: 8px;margin-bottom: 16px;user-select: text;margin-top: 8px;">
                {{ renderedMarkdown.think ? renderedMarkdown.think : '' }}
            </div>
            <div style="user-select: text;" v-html="renderedMarkdown.content"></div>
        </div>
        <!-- {{  )}} -->
        <!-- <char v-for="item in props.item.content" :anm="props.item.animation" :data="item" ></char> -->


        <div v-if="item.type === 2"
            style="width: 100%;text-align: center;font-size: 12px;color: dimgray;padding: 8px 0;">
            {{ displayContent }}
        </div>
        <div v-if="item.type === 0 && isTestMode && item.verbose && animationEnd"
            style="width: 100%;padding: 0px;border: 1px solid rgb(0,120,215);border-radius: 3px;font-size: 12px;">
            <div
                style="width: 100%;line-height: 16px;background-color: rgb(0,120,215);color: white;padding-left: 8px;display: flex;align-items: center;">
                <div style="width: 100%;height: 100%;align-items: center;word-break: keep-all;">调试信息</div>
                <div
                    style="width: 100%;height: 100%;display: flex;align-items: center;justify-content: flex-end;padding-right: 8px;">
                    <span @click="tool.copyToClipboard(JSON.stringify(item.verbose))"
                        style="text-decoration: underline;">复制</span>
                </div>
            </div>
            <div style="padding: 2px 4px;font-family: 'Courier New', Courier, monospace;line-height: 1.2;">
                <div style="width: 100%;font-family: sans-serif;line-height: 1.5;">
                    Total Latency:
                </div>
                <div style="width: 100%;">
                    {{ item.verbose.totalLatency }}
                </div>
                <div style="width: 100%;font-family: sans-serif;line-height: 1.5;">
                    Latency Per Token:
                </div>
                <div style="width: 100%;">
                    {{ item.verbose.latencyPerToken }} 毫秒
                </div>
                <div style="width: 100%;font-family: sans-serif;line-height: 1.5;">
                    Token Per Second:
                </div>
                <div style="width: 100%;">
                    {{ item.verbose.tokenPerSecond }} 个
                </div>
                <div style="width: 100%;font-family: sans-serif;line-height: 1.5;">
                    Input Token Ids({{ item.verbose.tokenIds.input.length }}):
                </div>
                <div style="width: 100%;white-space: wrap;overflow: hidden;">
                    <span :title="`index: ${index2}\n交换：${subItem.slice(2, 4) + subItem.slice(0, 2)}`"
                        style="word-break: keep-all;margin-right: 6px;text-decoration: underline;display: inline-block;"
                        v-for="(subItem, index2) in item.verbose.tokenIds.input">{{ subItem }}</span>
                </div>
                <div style="width: 100%;font-family: sans-serif;line-height: 1.5;">
                    Output Token Ids({{ item.verbose.tokenIds.output.length }}):
                </div>
                <div style="width: 100%;white-space: wrap;overflow: hidden;">
                    <span :title="`index: ${index2}\n交换：${subItem.slice(2, 4) + subItem.slice(0, 2)}`"
                        style="word-break: keep-all;margin-right: 6px;text-decoration: underline;display: inline-block;"
                        v-for="(subItem, index2) in item.verbose.tokenIds.output">{{ subItem }}</span>
                </div>
            </div>
        </div>
    </div>
    <div v-if="loading" style="width: 100%;padding: 8px 16px;padding-top:   3px;">
        <div style="width: 100%;height: 26px;display: flex;align-items: center;gap: 8px;">
            <img style="width: 24px;height: 24px;" src="../assets/icon_ruru_head.png" alt="">
            <span style="font-size: 15px;font-weight: bold;">圆如</span>
        </div>
        <div
            style="width: 100%;word-break: break-all;white-space: wrap;margin-top: 3px;font-size: 14px;padding-left: 27px;color: dimgray;user-select: text;white-space: pre-wrap;">
            正在思考...
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, defineProps, computed, watch, onMounted, onBeforeUnmount, nextTick, defineEmits } from 'vue';
import tool from '../tool';
import MarkdownIt from 'markdown-it';

const props = defineProps({
    item: {
        type: Object,
        default: {}
    },
    loading: {
        type: Boolean,
        default: false
    }
})

const mdi = new MarkdownIt({
    html: false,
    linkify: true,
});

const renderedMarkdown = computed(() => {
    window.MathJax.startup.defaultReady();
    let text = (() => {
        props.item.content = props.item.content.replaceAll('\n\n','\n')
        if (props.item.type === 0) {
            return props.item.content.replace(/(?<=\S) {1,2}(?=\S)/g, m => m.length === 2 ? ' ' : '') || ''
        } else {
            return props.item.content || '';
        }
    })()
    if (text.indexOf('<think>') === 0) {
        text = text.slice(7)
        text = text.split('</think>')
        return {
            think: text[0].replace(/^[\s\n]+|[\s\n]+$/g, ''),
            content: mdi.render(text[1] || '')
        }
    }
    return {
        content: mdi.render(text.replace(/^[\s\n]+|[\s\n]+$/g, ''))
    }
});

const isTestMode = ref(tool.store.getItem('testMode'))
tool.store.onChange('testMode', (e) => {
    isTestMode.value = e
})

const emits = defineEmits(['finished'])

const animationEnd = ref(false)

const displayContent = ref('')

let timer = null

const displayAnimation = () => {
    displayContent.value = ''
    clearInterval(timer)
    if (props.item.animation && false) {
        timer = setInterval(async () => {
            let current = displayContent.value
            let to = props.item.content
            if (current === to) {
                clearInterval(timer)
                tool.store.setItem('sending', false)
                emits('finished')
                animationEnd.value = true
                return
            }
            to = to.slice(current.length)
            to = to.slice(0, 1)
            displayContent.value += to
            await nextTick()
            tool.scrollToBottom('chatMsg')
            tool.scrollToBottom('chatMsgPC')
        }, 5);
    } else {
        displayContent.value = props.item.content
        tool.scrollToBottom('chatMsg')
        tool.scrollToBottom('chatMsgPC')
        animationEnd.value = true
    }
}

onMounted(async () => {
    tool.store.onChange('stop', () => {
        clearInterval(timer)
        tool.store.setItem('sending', false)
    })
    displayAnimation()
})
</script>

<style scoped></style>